package scau.mis4.chanyulin.base;

/**
 * Created by cyl on 2017/12/9.
 * 表示0和1组成的串
 */
public class Bits {

    private int length;
    private byte[] values;

    public Bits(int length) {
        this.length = length;
        values = new byte[length];
    }

    public Bits(byte[] values) {
        this.length = values.length;
        this.values = values;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public byte[] getValues() {
        return values;
    }

    public void setValues(byte[] values) {
        this.values = values;
    }

    public byte get(int i) {
        return values[i];
    }

    public void set(int i, int val) {
        if (val < 0 || val > 1) return;
        values[i] = (byte) val;
    }

    /**
     * 左移
     * @param movCount
     * @return
     */
    public Bits movLeft(int movCount) {
        movCount = movCount % this.length;
        if (movCount == 0) return this;
        Bits result = new Bits(this.length);
        byte[] temp = new byte[movCount];
        for (int i = 0; i < movCount; i++)
            temp[i] = this.get(i);
        for (int j = movCount; j < this.length; j++)
            result.set(j - movCount, this.get(j));
        for (int k = 0; k < movCount; k++)
            result.set(this.length - movCount + k, temp[k]);
        return result;
    }

    /**
     * 求异或
     * @param tar
     * @return
     */
    public Bits xor(Bits tar) {
        if (this.length != tar.length) return null;
        Bits result = new Bits(this.length);
        for (int i = 0; i < this.length; i++) {
            byte temp = this.get(i);
            temp ^= tar.get(i);
            result.set(i, temp);
        }
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (byte b : this.values)
            sb.append(b);
        return sb.toString();
    }

}
